﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Wolfy.NetDisk.Core.Service;
using Wolfy.NetDisk.Core.Model;
using System.IO;
using Wolfy.NetDisk.Core.Security;
namespace Wolfy.NetDisk.Site.Controllers
{
    public class BaseController : Controller
    {
        protected readonly IUserService userService;
        protected readonly INavigationService navigationService;
        protected readonly IImageManagerService imageManagerService;
        protected readonly ILogService logService;
        protected readonly IIconService iconService;
        public BaseController(IUserService userService, INavigationService navigationService, IImageManagerService imageManagerService)
        {
            this.userService = userService;
            this.navigationService = navigationService;
            this.imageManagerService = imageManagerService;
        }
        public BaseController(IUserService userService, INavigationService navigationService, IImageManagerService imageManagerService, ILogService logService, IIconService iconService)
            : this(userService, navigationService, imageManagerService)
        {
            this.logService = logService;
            this.iconService = iconService;
        }
        // GET: Base
        [Authorize(Roles = "普通用户,管理员")]
        public ActionResult Home()
        {
            //根据用户名获取用户信息           
            User user = userService.Where(o => o.UserName == User.Identity.Name).FirstOrDefault();
            if (user == null)
            {
                return RedirectToAction("SignIn", "account");
            }
            IEnumerable<Navigation> lstNavigations = null;
            if (HttpContext.User.IsInRole("管理员"))
            {
                lstNavigations = navigationService.Where(o => o.Role.Name == "管理员");
            }
            else
            {
                lstNavigations = navigationService.Where(o => o.Role.Name == "普通用户");
            }
            //foreach (var item in user.Files)
            //{
            //    item.Icon = iconService.Get(item.icon);
            //}
            TempData["user"] = user;
            ViewBag.user = user;
            logService.WriteLog(new Log { IsDeleted = false, LogType = LogType.Info, Conent = "访问Home", Op = "Home", User = user, Dt = DateTime.Now });
            return View(lstNavigations);
        }
        [HttpPost]
        [Authorize]
        public JsonResult PostedHeader()
        {
            var file = HttpContext.Request.Files[0];

            if (file == null)
            {
                return new JsonResult { Data = new { _msg = "没有选择文件", _code = 503 }, JsonRequestBehavior = JsonRequestBehavior.DenyGet };
            }
            string fileName = Path.GetFileName(file.FileName);
            string fileExt = Path.GetExtension(file.FileName);
            string[] allowUploadExts = { ".jpg", ".png", ".jpeg", ".gif" };
            if (!allowUploadExts.Contains(fileExt))
            {
                return new JsonResult { Data = new { _msg = "支持图片类型(.jpg,.png,.jpeg,.gif)", _code = 503 }, JsonRequestBehavior = JsonRequestBehavior.DenyGet };
            }
            string newFileName = MD5Hleper.GetMD5FromFile(file.InputStream) + fileExt;
            string fileSaveDir = Server.MapPath("~/Content/Headers");
            if (!Directory.Exists(fileSaveDir))
            {
                Directory.CreateDirectory(fileSaveDir);
            }
            string fileSavePath = Path.Combine(fileSaveDir, newFileName);
            //如果存在则不再保存物理文件，直接修改数据库
            if (!System.IO.File.Exists(fileSavePath))
            {
                imageManagerService.CompressImage(fileSavePath, file.InputStream, 80, 80);
            }

            //更新用户头像地址
            var currentUser = userService.Where(x => x.UserName == User.Identity.Name).FirstOrDefault();
            if (currentUser != null)
            {
                currentUser.Header = "/Content/Headers/" + newFileName;
            }
            userService.Update(currentUser);
            logService.WriteLog(new Log { Dt = DateTime.Now, User = currentUser, Op = "PostedHeader", Conent = "上传头像", LogType = LogType.Info, IsDeleted = false });
            return new JsonResult
            {
                Data = new
                {
                    _msg = "上传成功",
                    _code = 200,
                    _data = new
                    {
                        url = currentUser.Header
                    }
                },
                JsonRequestBehavior = JsonRequestBehavior.DenyGet
            };
        }
    }
}